<template>
    <div class="freight_template">
        <!-- 新增操作 -->
        <el-button
            class="freight_template_add_btn"
            v-auth="'delivery_management:freight_template'"
            type="primary"
            @click="routerHandler"
            >新增运费模板</el-button
        >
        <div class="freight_template_bottom">
            <!-- 列表 -->
            <el-table :data="tableList" :stripe="true">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template v-if="['operations'].includes(prop)" #default="{ row }">
                        <template v-if="prop === 'operations'">
                            <el-button
                                v-for="{ label, fn, ref, auth } in row.operations"
                                :key="label"
                                @click="fn(row, ref)"
                                size="small"
                                v-auth="auth"
                                :ref="el => setItemRef(el, `${ref}${row.id}`)"
                                class="table-button"
                                >{{ label }}</el-button
                            >
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </div>
        <!-- popover弹窗 -->
        <el-popover
            popper-class="custom-popovers-class not-close"
            ref="popoverRef"
            :virtual-ref="buttonRef"
            placement="top"
            trigger="click"
            virtual-triggering
            :effect="popoverText ? 'dark' : 'light'"
            :width="currentRow.ref === 'spreadButtonRef' ? 216 : 240"
            :visible="popoverVisible">
            <!-- todo:不同的内容 -->
            <div
                class="custom-popovers-class-main"
                v-click-outside="onClickOutside"
                v-if="['enabledButtonRef', 'disabledButtonRef', 'removeButtonRef'].includes(currentRow.ref)">
                <!-- 启用 -->
                <h3 style="margin-bottom: 16px" v-if="currentRow.ref == 'enabledButtonRef'">
                    <el-icon class="custom-icon"><WarningFilled /></el-icon>确定要启用该模板吗？
                </h3>
                <!-- 停用 -->
                <template v-if="currentRow.ref == 'disabledButtonRef' && popoverVisible">
                    <h3 v-if="!popoverText" style="margin-bottom: 16px">
                        <el-icon class="custom-icon"><WarningFilled /></el-icon>确定要停用该模板吗？
                    </h3>
                    <template v-if="popoverText">
                        {{ popoverText }}
                    </template>
                </template>
                <!-- 删除 -->
                <h3 style="margin-bottom: 16px" v-if="currentRow.ref == 'removeButtonRef'">
                    <el-icon class="custom-icon"><WarningFilled /></el-icon>确定要删除该模板吗？
                </h3>
                <div style="text-align: right" v-if="!popoverText && popoverVisible">
                    <el-button size="small" @click="popoverVisibleHandler()">取消</el-button>
                    <el-button size="small" type="primary" @click="popoverConfirmHandler()">确定</el-button>
                </div>
            </div>
            <div class="custom-popovers-class-main" v-click-outside="onClickOutside" v-else>
                {{ popoverText }}
            </div>
        </el-popover>
    </div>
</template>

<script setup name="freightTemplate">
import { ref, unref, reactive, computed, onMounted, onUnmounted, onActivated, onDeactivated, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ClickOutside as vClickOutside } from 'element-plus';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil, downloadImgHandler } from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';
import Pagination from '@/components/Pagination.vue';
import { cloneDeep } from '@/commons/utils';
import store from '@/store/index';
import storage from '@/commons/storage';

const router = useRouter();
const activityStatusList = reactive(packSelectObjUtil(constants.GROUP_STATUS_OPTIONS));
const activityType = reactive(packSelectObjUtil(constants.ACTIVITY_TYPE));

// todo:优化代码结构
const form = reactive({
    page: 1, //分页页码，数字类型
    perPage: 10 //默认每页15条
});
let formClone = reactive(null);
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);
let popoverText = ref();
let isEdit = ref(false);

// popover ref
let popoverVisible = ref(false);
const itemRefs = {};
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};
const popoverRef = ref(null);
const buttonRef = ref(null);
let currentRow = reactive({ ref: null, id: null, status: null });

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '模板名称', prop: 'name', showOverflowTooltip: true, minWidth: '250' },
        { label: '说明', prop: 'description', showOverflowTooltip: true, minWidth: '250' },
        { label: '状态', prop: 'enableText', width: '80' },
        { label: '更新时间', prop: 'createdAt', width: '190' },
        { label: '操作', prop: 'operations', width: '210', fixed: 'right' }
    ];
    return baseTableColumns;
});

const nameRouteHandler = ({ id }, type) => {
    const useAuth = store.useAuthStore();
    const permissions = useAuth.permissions;
    const code = 'freight_list:view';
    if (!permissions.has(code)) {
        ElMessage({
            type: 'error',
            message: '当前用户没有查看权限'
        });
        return false;
    }
    const { href } = router.resolve({
        path: '/marketing/freight/detail',
        query: {
            id,
            type
        }
    });
    window.open(href, '_blank');
};
const routerHandler = () => {
    // 跳转新增运费模板
    isEdit.value = true;
    router.push({ path: '/order/delivery/templateAdd' });
};
// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const res = await request('getfreightList', { shopId: storage.get('ZW-SHOPID'), ...form });
    const list = (res?.data?.list || []).map(item => {
        // todo: 根据不同状态显示不同按钮
        // todo:权限
        item.enableText = item.enable == 1 ? '已启用' : '已停用';
        // item.description = item.description || '-';
        const btns = [
            { label: '编辑', fn: editHandler, ref: 'editButtonRef', auth: 'delivery_management:freight_template' },
            {
                label: '停用',
                fn: disabledHandler,
                ref: 'disabledButtonRef',
                auth: 'delivery_management:freight_template'
            },
            {
                label: '启用',
                fn: enabledHandler,
                ref: 'enabledButtonRef',
                auth: 'delivery_management:freight_template'
            },
            { label: '删除', fn: removeHandler, ref: 'removeButtonRef', auth: 'delivery_management:freight_template' }
        ];
        if (item.enable == 1) {
            item.operations = [btns[0], btns[1]];
        } else if (item.enable == 2) {
            item.operations = [btns[0], btns[2], btns[3]];
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.totalCount;
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryCouponListHandler();
};
/** 按钮组操作 */
const popoverHandler = ({ id, enable }, ref) => {
    buttonRef.value = itemRefs[`${ref}${id}`];
    currentRow.ref = ref;
    currentRow.id = id;
    currentRow.enable = enable;

    nextTick(() => {
        popoverVisible.value = true;
    });
};
// 编辑
const editHandler = row => {
    isEdit.value = true;
    router.push({
        path: '/order/delivery/templateEdit',
        query: {
            id: row.id
        }
    });
};
// 启用
const enabledHandler = (row, ref) => {
    popoverHandler(row, ref);
};
// 停用
const disabledHandler = async (row, ref) => {
    // todo:验证是否能停用
    const { msg } = await request('freightNotify', { id: row.id });
    if (msg) {
        popoverText.value = msg;
    }
    popoverHandler(row, ref);
};
// 删除
const removeHandler = (row, ref) => {
    popoverHandler(row, ref);
};
// 点击popover外部
const onClickOutside = el => {
    popoverVisibleHandler();
};
// 控制popover展示隐藏
const popoverVisibleHandler = (visible = false) => {
    if (!visible) {
        popoverText.value = null;
    }
    popoverVisible.value = visible;
};
// popover确定
const popoverConfirmHandler = async () => {
    const apiName = {
        disabledButtonRef: 'freightSwitch',
        removeButtonRef: 'freightDel',
        enabledButtonRef: 'freightSwitch'
    };
    let params = null;
    if (['disabledButtonRef', 'enabledButtonRef'].includes(currentRow.ref)) {
        params = {
            shopId: storage.get('ZW-SHOPID'),
            templateId: currentRow.id,
            enable: currentRow.enable == 1 ? 2 : 1
        };
    } else {
        params = {
            id: currentRow.id
        };
    }
    await request(apiName[currentRow.ref], params);
    popoverVisibleHandler();
    queryCouponListHandler();
    ElMessage({
        type: 'success',
        message: '操作成功'
    });
};

const getAllData = () => {
    searchHandler();
};

onMounted(() => {
    if (isEdit.value) {
        queryCouponListHandler();
        isEdit.value = false;
    } else {
        form.pageSize = 10;
        getAllData();
    }
    // setLayout();
});
onUnmounted(() => {
    // resetLayout();
});

onActivated(() => {
    if (isEdit.value) {
        queryCouponListHandler();
        isEdit.value = false;
    } else {
        form.pageSize = 10;
        getAllData();
    }
    // setLayout();
});
onDeactivated(() => {
    // resetLayout();
});
</script>
<style lang="scss">
.custom-popovers-class {
    padding: 0 !important;
    h3,
    p {
        margin: 0;
    }
    h3 {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        .custom-icon {
            width: 14px;
            height: 14px;
            margin-right: 9px;
            color: #faad14;
            margin-top: 2px;
        }
    }

    p {
        padding-left: 23px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        line-height: 16px;
        margin: 0 0 16px;
    }

    p + div {
        text-align: right;
    }

    .custom-preview {
        margin-top: 16px;
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
    }

    &-main {
        padding: 16px;
    }
}
</style>
<style lang="scss" scoped>
@import './index.scss';
</style>
